package com.ruben.controller;

import com.ruben.constant.UserConstant;
import com.ruben.pojo.User;
import com.ruben.pojo.po.UserPO;
import com.ruben.service.UserService;
import com.ruben.utils.AjaxJson;
import com.ruben.utils.Encrypt;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeiboRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;


@RestController
@RequestMapping("/oauth/weibo")
public class RestAuthController {

    @Resource
    private UserService userService;

    /**
     * 转发到第三方
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 回调接口
     *
     * @param callback
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/callback")
    public Object login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        //判断是否成功
        if (response.ok()) {
            //获取用户
            AuthUser authUser = response.getData();
            //判断UUid和平台是否存在于数据库
            User user = userService.getUserByUuid(authUser.getUuid());
            //不存在就注册一个
            if (user == null) {
                user = new User();
                //设置uuid
                user.setUuid(authUser.getUuid());
                //设置用户名
                user.setUsername(authUser.getUsername());
                //设置密码
                user.setPassword(Encrypt.SHA512(UserConstant.SALT + user.getUsername() + UUID.randomUUID().toString().replace("-", "")));
                user = userService.createUser(user);
            }
            UserPO userPO = new UserPO();
            BeanUtils.copyProperties(user, userPO);
            //登录，返回Token
            return AjaxJson.success("登录成功！")
                    .put("token", userService.createToken(userPO, UserConstant.TOKEN_EXPIRE_TIME))
                    .put("refreshToken", userService.createToken(userPO, UserConstant.REFRESH_TOKEN_EXPIRE_TIME));
        }
        //返回错误信息
        return AjaxJson.error("登陆失败").put("data", response.getMsg());
    }

    /**
     * 取消授权
     *
     * @param token
     * @return
     * @throws IOException
     */
    @RequestMapping("/revoke/{token}")
    public Object revokeAuth(@PathVariable("token") String token) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        return authRequest.revoke(AuthToken.builder().accessToken(token).build());
    }

    /**
     * 获取request
     *
     * @return
     */
    private AuthRequest getAuthRequest() {
        return new AuthWeiboRequest(AuthConfig.builder()
                .clientId("")
                .clientSecret("")
                .redirectUri("http://vampireachao.utools.club/oauth/weibo/callback")
                .build());
    }
}
